using System;
using System.Collections.Generic;
using System.Text;
using Db4objects.Db4o;
using System.IO;

namespace Midas.Core
{
	public abstract class DatabaseManager
	{
		private static string initialRootAdminPass;

		public static string InitialRootAdminPass
		{
			get { return DatabaseManager.initialRootAdminPass; }
			set { DatabaseManager.initialRootAdminPass = value; }
		}
		private static IObjectServer server;
		internal static IObjectServer DatabaseServer
		{
			get
			{
				if (server == null)
				{
					string dir=Directory.GetCurrentDirectory(),separator;
					if(!dir.EndsWith(separator=Path.DirectorySeparatorChar.ToString()))
						dir+=separator;
					dir += "db";
					if(!Directory.Exists(dir))
						Directory.CreateDirectory(dir);
					server=Db4oFactory.OpenServer(string.Format(@"db{0}midas.db",separator),0);
					IObjectContainer client = server.OpenClient();
					if (client.Query<Admin>().Count == 0)
					{
						client.Set(new Admin("root",initialRootAdminPass));
					}
					client.Commit();
					client.Close();
				}
				return server;
			}
		}

		public static int GetNumberOfInstances<T>()
		{
			using (IObjectContainer client = DatabaseServer.OpenClient())
			{
				return client.Query<T>().Count;
			}
		}

	}
}
